#!/usr/bin/env -S node -r ./livescript-transform-implicit-async/register

require! <[
  ./confirm
  ./log
  ./argv
  ./Git.ls
  ./cache-dir.ls
  ./upgrade.ls
  axios
  chalk
  path
]>

require! {
  \fs-extra : fs
  \js-yaml : yaml
}


GIT-YAML = \git.yaml


_UPGRADE = []

_install = (url)~>
  if url.indexOf("://") < 0
    url = "https://"+url
  dir = cache-dir.git(url)
  is-new = await Git(dir).npm-install url
  if not is-new
    _UPGRADE.push upgrade(dir)
  [dir,is-new]

_upgrade = !~>
  for i in await Promise.all(_UPGRADE)
    await i?!

_json-install = (o)~>
  npm-install = require \./npm-install.ls
  for k,v of o
    if typeof(v) == \string
      o[k] = (await _install v)[0]
    else if Array.isArray(v)
      li = []
      for i in v
        li.push (await _install i)[0]
      o[k] = li
    else
      r = {}
      for git, config of v
        [p,is-new] = await _install git
        r[p] = config
        if is-new
          for action, dir of config
            if not Array.isArray(dir)
              dir = Object.keys dir
            for d in dir
              await npm-install path.join p,d
      o[k] = r
  o

_yaml-install = (data)~>
  _json-install yaml.load data

init = (argv)!~>
  {boot-url,cwd, boot-dir} = argv
  {data} = await axios.get boot-url
  p = path.join(
    cwd
    boot-dir
    GIT-YAML
  )
  console.log chalk.yellowBright("\n➜ ")+chalk.greenBright(p) + chalk.green(' 配置文件已写入')
  console.log chalk.yellowBright(data)
  r = await _yaml-install data
  await fs.output-file p, data
  argv.config = r
  try
    await require(path.join(r.sh, \init))(argv)
  catch err
    console.trace!
    log.err err
  return r

run = (argv)!~>
  Object.assign(
    require path.join(
      argv.config.sh
      \./argv
    )
    argv
  )

  # 加载项目脚本的参数帮助，然后再返回
  if argv.help
    return

  if not argv.upgrade
    try
      await require(argv.config.sh)!
    catch err
      console.trace!
      console.error err
  await _upgrade!


module.exports = !~>

  cwd = argv.cwd
  argv.boot-dir = boot-dir = path.basename(argv.boot-url).slice(0,-5)

  _load = ~>
    config = path.join boot-dir, GIT-YAML
    p = path.join(cwd, config)
    if await fs.exists p
      argv.config = await _yaml-install await fs.readFile p, \utf-8
      argv.cwd = cwd
      await run(argv)
      return true

  if cwd
      if await _load!
        return
  else
    cwd = pwd = process.cwd()

    while 1
      if await _load!
        return

      _dir = path.resolve cwd, \..

      if _dir == cwd
        break

      cwd = _dir

    cwd = pwd

  if argv.upgrade or argv.help
    return

  if argv.yes or await confirm("项目不存在，在 #cwd 初始化吗")
    argv.cwd = cwd
    argv.config = await init(argv)
  else
    return

  await run argv

if require.main == module
  module.exports!
